/**
 * 
 */
package server.alarmThreads;

import net.sourceforge.prowl.api.DefaultProwlEvent;
import net.sourceforge.prowl.api.ProwlClient;
import net.sourceforge.prowl.api.ProwlEvent;
import net.sourceforge.prowl.exception.ProwlException;

import org.apache.log4j.Logger;

import server.config.ServerConfig;
import server.container.JPushInfo;

/**
 * @author Christian
 * 
 */
public class ProwlAlarmierer {

	private static Logger logger = Logger.getLogger(ProwlAlarmierer.class);

	public void alarmiere(JPushInfo info) {

		final StringBuffer builder = new StringBuffer();
		builder.append("-----Prowl alamierung gestartet-----\n");

		if (!ServerConfig.getInstance().isDebug()) {
			ProwlClient c = new ProwlClient();
			try {
				int i = 0;
				int wiederholungen = 1;
				if (info.getPrioritaet() >= 2) {
					wiederholungen = 4;
				}
				builder.append(info.getUserAPIKey() + " Priorität:"
						+ info.getPrioritaet());
				builder.append("\n");
				while (i < wiederholungen) {
					String alarmText = info.getAlarm().toString();
					if (wiederholungen > 1) {
						alarmText = info.getAlarm().toString() + "  " + i;
					}
					ProwlEvent e = new DefaultProwlEvent(info.getUserAPIKey(),
							"Einsatzalarm", info.getAlarm().getEinsatzArt(),
							alarmText, info.getPrioritaet());
					builder.append(c.pushEvent(e));
					builder.append("\n");
					// 1 Sekunde warten
					sleep(1000);
					i++;
				}
			} catch (ProwlException e1) {
				builder.append(e1.getMessage());
				builder.append("\n");
				logger.error("Prowl-Fehler", e1);
			} catch (Exception e) {
				builder.append(e.getMessage());
				builder.append("\n");
				logger.error("Prowl-Fehler", e);
			}
		}

		builder.append("-----Nachricht ueber Prowl gesendet------");
		logger.info(builder.toString());

	}

	/**
	 * 
	 * @param sleep
	 *            Sleep
	 */
	private static void sleep(long sleep) {

		try {
			Thread.sleep(sleep);
		} catch (InterruptedException e) {
			logger.error("", e);
		}
	}
}
